//
//  MineLoginController.swift
//  HappyEat
//
//  Created by ctx2016 on 17/1/20.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SwiftyJSON

class MineLoginController: UIViewController ,UITextFieldDelegate{
    
    var viewFrame:CGRect = .zero
    
    var userDefault:UserDefaults = UserDefaults.standard
    
    var phoneTextField:UITextField = UITextField.init()
    
    var mimaTextField:UITextField = UITextField.init()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNavi()
    }
}
extension MineLoginController {
    //MARK:设置导航栏选项
    func setNavi(){
        self.navigationItem.title = "账号登录"
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black]
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_back", fontSize: 14, target: self, action: #selector(leftBarButtonAction))
    }
    //MARK:LeftBarButtonAction
    func leftBarButtonAction(){
        self.navigationController!.popViewController(animated: false)
    }
    func setUI(){
        self.viewFrame = self.view.frame
        let tapHideKeyBoard:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(hideKeyboard))
        self.view.addGestureRecognizer(tapHideKeyBoard)
        let touxiangIcon:UIImageView = UIImageView.init(image: UIImage.init(named: "zhanghu"))
        let mimaIcon:UIImageView = UIImageView.init(image: UIImage.init(named: "mima"))
        self.view.addSubview(touxiangIcon)
        self.view.addSubview(mimaIcon)
        self.view.addSubview(self.phoneTextField)
        self.view.addSubview(self.mimaTextField)
        self.phoneTextField.delegate = self
        self.mimaTextField.delegate = self
        let phoneDownView:UIView = UIView.init()
        phoneDownView.backgroundColor = .gray
        self.phoneTextField.placeholder = "请输入手机号码"
        self.view.addSubview(phoneDownView)
        touxiangIcon.snp.makeConstraints { (make) in
            make.top.equalTo(136/2 + 64)
            make.left.equalTo(24)
            make.size.equalTo(CGSize.init(width: 24, height: 24))
        }
        self.phoneTextField.snp.makeConstraints { (make) in
            make.left.equalTo(touxiangIcon.snp.right).offset(12)
            make.height.equalTo(16)
            make.right.equalTo(-24)
            make.top.equalTo(touxiangIcon.snp.top).offset(4)
        }
        phoneDownView.snp.makeConstraints { (make) in
            make.left.equalTo(self.phoneTextField)
            make.top.equalTo(self.phoneTextField.snp.bottom).offset(18)
            make.height.equalTo(0.5)
            make.right.equalTo(-24)
        }
        mimaIcon.snp.makeConstraints { (make) in
            make.left.equalTo(24)
            make.top.equalTo(phoneDownView.snp.bottom).offset((52-24)/2)
            make.size.equalTo(CGSize.init(width: 24, height: 24))
        }
        let mimaDownView:UIView = UIView.init()
        mimaDownView.backgroundColor = .gray
        self.view.addSubview(mimaDownView)
        self.mimaTextField.snp.makeConstraints { (make) in
            make.left.equalTo(mimaIcon.snp.right).offset(12)
            make.top.equalTo(phoneDownView.snp.bottom).offset(18)
            make.right.equalTo(-24)
            make.height.equalTo(16)
        }
        self.mimaTextField.placeholder = "请输入账号密码"
        mimaDownView.snp.makeConstraints { (make) in
            make.top.equalTo(self.mimaTextField.snp.bottom).offset(18)
            make.left.equalTo(mimaIcon.snp.right).offset(12)
            make.right.equalTo(-24)
            make.height.equalTo(0.5)
        }
        let loginButton:UIButton = UIButton.init()
        self.view.addSubview(loginButton)
        loginButton.setTitle("登录", for: .normal)
        loginButton.setTitleColor(.white, for: .normal)
        loginButton.backgroundColor = .red
        loginButton.layer.cornerRadius = 5.0
        loginButton.addTarget(self, action: #selector(loginAction(_ :)), for: .touchUpInside)
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(mimaDownView.snp.bottom).offset(50)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(40)
        }
        
        let forgetMimaButton:UIButton = UIButton.init()
        let registButton:UIButton = UIButton.init()
        self.view.addSubview(forgetMimaButton)
        self.view.addSubview(registButton)
        forgetMimaButton.setTitleColor(BaseFontColor, for: .normal)
        forgetMimaButton.setTitle("忘记密码", for: .normal)
        registButton.setTitle("注册账号", for: .normal)
        registButton.setTitleColor(BaseFontColor, for: .normal)
        registButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        forgetMimaButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        forgetMimaButton.addTarget(self, action: #selector(forgetButtonAction), for: .touchUpInside)
        registButton.addTarget(self, action: #selector(registButtonAction), for: .touchUpInside)
        let label:UILabel = UILabel.init()
        forgetMimaButton.snp.makeConstraints { (make) in
            make.left.equalTo(24)
            make.width.equalTo(label.width(forText: "忘记密码", withFontSize: 14, withTextHeight: 14)+10)
            make.height.equalTo(16)
            make.top.equalTo(loginButton.snp.bottom).offset(12)
        }
        registButton.snp.makeConstraints { (make) in
            make.right.equalTo(-24)
            make.top.equalTo(forgetMimaButton)
            make.width.equalTo(label.width(forText: "注册账号", withFontSize: 14, withTextHeight: 14)+10)
            make.height.equalTo(16)
        }
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.phoneTextField {
            
            var frameOrign:CGRect = self.viewFrame
            frameOrign.origin.y = -10
            UIView.animate(withDuration: 0.3, animations: { 
               self.view.frame = frameOrign
            })
        }else if textField == self.mimaTextField{
            var frameOrign:CGRect = self.viewFrame
            frameOrign.origin.y = -20 - 20
            UIView.animate(withDuration: 0.3, animations: {
                self.view.frame = frameOrign
            })
        }
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        UIView.animate(withDuration: 0.3) { 
            self.view.frame = self.viewFrame
        }
        return true
    }
    func hideKeyboard(){
        self.phoneTextField.resignFirstResponder()
        self.mimaTextField.resignFirstResponder()
        UIView.animate(withDuration: 0.3) {
            self.view.frame = self.viewFrame
        }
    }
    //MARK:注册和忘记密码事件
    func registButtonAction(){
        let vc:MineRegistController = MineRegistController()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    func forgetButtonAction(){
        let vc:MineForgetMiMaController = MineForgetMiMaController()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    //MARK:loginAction
    func loginAction(_ button:UIButton){
        let whiteSet = NSCharacterSet.whitespacesAndNewlines
        var phoneStr:NSString = self.phoneTextField.text as?NSString ?? ""
        var passWord:NSString = self.mimaTextField.text as?NSString ?? ""
        phoneStr = phoneStr.trimmingCharacters(in: whiteSet) as NSString
        passWord = passWord.trimmingCharacters(in: whiteSet) as NSString
        let requstNet:NetworkRequest = NetworkRequest.shareInstance
        if !(phoneStr.length>0)&&(passWord.length>0){
            return
        }
        let params:[String:String] = ["phone":phoneStr as String,"password":passWord as String]
        requstNet.postRequest(urlString: Login_URL, params: params, success: { (success) in
            print(success)
            let dic = JSON(success)
            if dic["status"].stringValue == "SUCCESS"{
                let dataDic = dic["data"]
                self.userDefault.set(dataDic["id"].stringValue, forKey: ID)
                self.userDefault.set(dataDic["phone"].stringValue , forKey: PHONE)
                self.userDefault.set(passWord, forKey: PASSWWORD)
                self.userDefault.set(dataDic["nickname"].stringValue, forKey: NICKNAME)
                self.userDefault.set(dataDic["headImg"].stringValue, forKey: HEADIMGE)
                self.userDefault.set(dataDic["registerTime"].stringValue, forKey: REGISTTIME)
                self.userDefault.set(dataDic["lastLoginTime"].stringValue, forKey: LASTLOGINTIME)
                self.userDefault.set(dataDic["status"].stringValue, forKey: STATUS)
                self.userDefault.set(dataDic["balance"].stringValue, forKey: BALANCE)
                self.userDefault.set(dataDic["points"].stringValue, forKey: POINTS)
                self.userDefault.set(dataDic["inviteCode"].stringValue, forKey: INVITECODE)
                self.userDefault.set(dataDic["verifyCode"].stringValue, forKey: VERIFYCODE)
                self.userDefault.synchronize()
                self.navigationController!.popToRootViewController(animated: true)
            }else if dic["status"].stringValue == "ERROR"{
                //报错信息
                print(dic["error"])
            }
            }) { (error) in
                //请求服务异常
                print(error)
        }
    }
}
